package com.rc.saas.tenant.controller.order;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.order.OrderDiscountRecordSearch;
import com.rc.saas.tenant.service.order.OrderDiscountRecordService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.order.ExportOrderDiscountRecordVo;
import com.rc.saas.tenant.vo.order.OrderDiscountRecordVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;


/**
 * @author zhongz
 * @data 20220723
 */
@Controller
@RequestMapping("/orderDiscount")
public class OrderDiscountController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private OrderDiscountRecordService orderDiscountRecordService;

    /**
     * 跳转充电管理/优惠列表页面
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String orderDiscountRecordPage() {
        return "/templates/order/orderDiscountRecordList";
    }


    /**
     * 优惠列表数据
     * @return
     */
    @RequestMapping(value = "/listOrderDiscountRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listOrderDiscountRecord(OrderDiscountRecordSearch search) {
        TenantUser user = ShiroUtils.getSessionUser();
        search.setLoginName(user.getLoginName());
        PageInfo<OrderDiscountRecordVo> pageInfo = orderDiscountRecordService.searchByCondition(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 删除优惠列表数据
     * @param id
     * @return
     */
    @RequestMapping(value = "/delOrderDiscountRecord", method = RequestMethod.POST)
    @ResponseBody
    public TResponse delOrderDiscountRecord(String id) {
        if (StringUtils.isBlank(id)){
            return TResponse.FAIL("参数错误");
        }
        TenantUser user = ShiroUtils.getSessionUser();
        Long orderDiscountId = Long.parseLong(id);
        orderDiscountRecordService.delOrderDiscountRecord(orderDiscountId, user.getLoginName());
        return TResponse.SUCCESS();
    }
    /**
     * 删除优惠列表数据
     * @param idList
     * @return
     */
    @RequestMapping(value = "/batchDelOrderDiscountRecord", method = RequestMethod.POST)
    @ResponseBody
    public TResponse batchDelOrderDiscountRecord(@RequestParam("idList") List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return TResponse.FAIL("参数错误");
        }
        TenantUser user = ShiroUtils.getSessionUser();
        for (Long orderDiscountId : idList) {
            orderDiscountRecordService.delOrderDiscountRecord(orderDiscountId, user.getLoginName());
        }
        return TResponse.SUCCESS();
    }


    /**
     * 导出优惠列表数据
     */
    @ResponseBody
    @RequestMapping("/exportOrderDiscountRecord")
    public TResponse exportOrderDiscountRecord(OrderDiscountRecordSearch search, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        ExportUtils.setDefaultPaging(search);
        if (search.getCount() == 0 || search.getCount() == null) {
            search.setCount(search.getLimit());
        }
        if (search.getCount() > 200000) {
            return TResponse.FAIL("最多导出二十万数据");
        }
        if (search.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        search.setOffset(search.getLimit() * (search.getOffset() - 1));
        List<ExportOrderDiscountRecordVo> list = orderDiscountRecordService.exportOrderDiscountRecord(search);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("优惠信息列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExportOrderDiscountRecordVo.class).sheet("优惠信息列表").doWrite(list);
            return null;
        } catch (Exception e) {
            logger.error("导出优惠信息列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

}
